﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ECommerce.BLL.Product;
using ECommerce.Model.Product;
using Jzy.Core.Utility;
using ECommerce.BLL.Order;
using ECommerce.BLL.Member;
using ECommerce.Model.Member;
using ECommerce.Common;
using ECommerce.Model.Order;
using Jzy.Core.Common.Web;
using Jzy.Core.Log.Exceptions;
using Jzy.Core.Dict;
using Jzy.Core.Common;

namespace ECommerce.Web.Site
{
    public partial class Shopping2 : SitePage
    {
        private ECProductBO Product
        {
            get
            {
                return ECProductBO.Instance<ECProductBO>();
            }
        }

        private MemberBaseBO Member
        {
            get
            {
                return MemberBaseBO.Instance<MemberBaseBO>();
            }
        }



        private ECOrderBO Order
        {
            get
            {
                return ECOrderBO.Instance<ECOrderBO>();
            }
        }

        private ECOrderProductBO OrderProduct
        {
            get
            {
                return ECOrderProductBO.Instance<ECOrderProductBO>();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            base.CheckLogin();

            if (Request.Cookies["ShoppingCart"] == null)
            {
                string script = "alert('请选择蛋糕');location.href='shopping1.aspx';";
                JSUtil.ResponseJS(script);
            }

            if (!IsPostBack)
            {
                this.DeliverTime.Text = DateTime.Now.AddDays(3).ToString("yyyy-MM-dd");
                //判断购物车是否为空
                BindView();

                BindArea();
            }
            AddAttr();
        }

        private void BindArea()
        {
            DictBO dict = new DictBO();
            //dict.BindListControl(drpArea, (int)DictItem.门店区域);
            //IEnumerable<DictInfo> list = dict.GetList((int)DictItem


            //if (drpArea.Items.Count > 0)
            //{
            //    drpArea.SelectedIndex = 0;

            //    BindAddress(int.Parse(drpArea.SelectedValue));
                
            //}

            dict.BindListControl(RecieveArea, (int)DictItem.门店区域);
            dict.BindListControl(SendArea, (int)DictItem.门店区域);

            DeliverPart.Items.Add(new ListItem("上午", "上午"));
            DeliverPart.Items.Add(new ListItem("下午", "下午"));

            List<EnumInfo> list = ConvertUtil.ConvertEnum(typeof(BigArea));
            this.BigArea.DataSource = list;
            this.BigArea.DataTextField = "Name";
            this.BigArea.DataValueField = "ID";
            this.BigArea.DataBind();


            this.RecieveBigArea.DataSource = list;
            this.RecieveBigArea.DataTextField = "Name";
            this.RecieveBigArea.DataValueField = "ID";
            this.RecieveBigArea.DataBind();


        }

        //private void BindAddress(int areaID)
        //{
        //    ECStoreBO store = new ECStoreBO();
        //    List<ECStoreInfo> list = store.GetList(areaID);
        //    lstAddress.DataSource = list;
        //    lstAddress.DataTextField = lstAddress.DataValueField = "Address";
        //    lstAddress.DataBind();
        //    lstAddress.SelectedIndex = 0;
        //}
        private void AddAttr()
        {
            WebUtil.SetTimeBox(this.DeliverTime, false);
        }
       

        private void BindView()
        {
            string shoppingCart = null;
            if (Request.Cookies["ShoppingCart"] != null)
            {
                shoppingCart = Request.Cookies["ShoppingCart"].Value;
            }

            if (!string.IsNullOrEmpty(shoppingCart))
            {

                double totalValue;

                List<ECProductInfo> list = GetCartList(shoppingCart,out totalValue);

                rpt.DataSource = list;
                rpt.DataBind();

                litTotalPrice.Text = totalValue.ToString("c2");
                litFreight.Text = 15.ToString("c2");

                litProductCount.Text = list.Sum(T => T.BuyCount).ToString();

                
            }
            else
            {
                string script = "alert('请选择蛋糕');location.href='shopping1.aspx';";
                JSUtil.ResponseJS(script);
            }
        }

        private List<ECProductInfo> GetCartList(string shoppingCart, out double totalValue)
        {
            string[] idCounts = shoppingCart.Split(',');

            List<ECProductInfo> tmpInfos = new List<ECProductInfo>();
            foreach (string idcount in idCounts)
            {
                ECProductInfo info = new ECProductInfo();
                info.ID = int.Parse(idcount.Split('_')[0]);
                info.BuyCount = int.Parse(idcount.Split('_')[1]);
                info.Size = Server.UrlDecode(idcount.Split('_')[2]);
                tmpInfos.Add(info);
            }

            MemberBaseInfo memberInfo = this.Member.GetInfo(SiteSession.MemberID);

            List<ECProductInfo> list = this.Product.GetList(tmpInfos.Select(T => T.ID));
            totalValue = 0;
            foreach (ECProductInfo info in list)
            {
                ECProductInfo tmpInfo = tmpInfos.Where(T => T.ID == info.ID).First();
                info.BuyCount = tmpInfo.BuyCount;

                info.Size = tmpInfo.Size;

                double unitPrice = (memberInfo.Level == (int)MemberLevel.VIP) ? info.VipPrice : info.CurrentPrice;
                totalValue += unitPrice * info.BuyCount;

            }
            return list;
        }
        protected void btnNext_Click(object sender, EventArgs e)
        {
            MemberBaseInfo memberInfo = this.Member.GetInfo(SiteSession.MemberID);
            ECOrderInfo info = new ECOrderInfo();

            EntityUtil.SetEntity(pnlMain, info);
            info.SendGender = Request.Form["SendGender"];
            info.RecieveGender = Request.Form["RecieveGender"];
            //info.Anonymity = Request.Form["Anonymity"] == "1";
            info.InputTime = DateTime.Now;
            info.MemberID = SiteSession.MemberID;
            info.MemberLoginName = SiteSession.MemberLoginName;
            //info.MemberRemain = memberInfo.Remain;
            info.OrderState = (int)OrderState.未处理;
            info.PayState = (int)PayState.未支付;
            info.PayMode = (int)PayMode.在线支付;
            info.LogisticsType = (int)LogisticType.送货上门;
            //if (info.LogisticsType == (int)LogisticType.门店自取)
            //{
            //    info.TakeAddress = lstAddress.SelectedValue;
            //}
            //else
            //{
                info.RecieveArea = RecieveArea.SelectedItem.Text;
            //}
            info.SendArea = SendArea.SelectedItem.Text;

            info.DeliverPart = this.DeliverPart.SelectedValue;
            info.InvoiceTarget = (int)InvoiceTarget.个人; //int.Parse(Request.Form["InvoiceTarget"]);
            //info.InvoiceHead = this.InvoiceHead.Text;

           
            this.OrderProduct.dbOper = this.Order.dbOper = this.Member.dbOper;
            try
            {                

                Order.dbOper.BeginTrans();

                info.MemberRemain = this.Member.GetRemain(SiteSession.MemberID);
                info.ID = this.Order.GetOrderID();

                Order.Save(info, true);

                double totalValue = 0;
                List<ECProductInfo> list = GetCartList(Request.Cookies["ShoppingCart"].Value,out totalValue);
                
                foreach (ECProductInfo productInfo in list)
                {
                    ECOrderProductInfo orderProductInfo = new ECOrderProductInfo();
                    orderProductInfo.BuyNumber = productInfo.BuyCount;
                    orderProductInfo.OrderID = info.ID;
                    orderProductInfo.ProductID = productInfo.ID;
                    orderProductInfo.ProductName = productInfo.Name;
                    orderProductInfo.Size = productInfo.Size;
                    orderProductInfo.UnitPrice = (memberInfo.Level == (int)MemberLevel.VIP) ? productInfo.VipPrice : productInfo.CurrentPrice;
                    orderProductInfo.TotalPrice = orderProductInfo.UnitPrice * orderProductInfo.BuyNumber;
                    OrderProduct.Save(orderProductInfo);
                }

                info.TradeValue = totalValue;

                if (info.RecieveBigArea == (int)ECommerce.Model.Order.BigArea.中环线以内)
                {
                    info.Freight = 15;
                }
                else
                {
                    info.Freight = 30;
                }

                string payMode = Request.Form["interface"];
                if (payMode == "2")
                {
                    info.PayMode = (int)PayMode.货到付款;
                }

                this.Order.Save(info);

                HttpCookie cookie = new HttpCookie("ShoppingCart", "");
                cookie.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(cookie);


                if (info.TradeValue + info.Freight > info.MemberRemain)//余额不够支付，转支付页面
                {
                    ////生成支付订单
                    //ECOrderPayBO orderPay = new ECOrderPayBO();
                    //orderPay.dbOper = Order.dbOper;
                    //ECOrderPayInfo payInfo = new ECOrderPayInfo();
                    //payInfo.ID = this.Order.GetOrderID();
                    //payInfo.OrderID = info.ID;
                    //payInfo.MemberID = SiteSession.MemberID;
                    //payInfo.MemberLoginName = SiteSession.MemberLoginName;
                    //payInfo.MemberRemain = info.MemberRemain;
                    //payInfo.Amount = info.TradeValue + info.Freight;
                    //payInfo.State = (int)PayState.未支付;
                    //payInfo.PayInterface = (int)PayInterface.网银在线;
                    //orderPay.Save(payInfo,true);


                    Order.dbOper.CommitTrans();



                    if (payMode == "0")
                    {
                        Response.Redirect("Send.aspx?OrderID=" + StrUtil.EncryptUrl(info.ID));
                    }
                    else if (payMode == "1")
                    {
                        Response.Redirect("../Alipay/Send.aspx?OrderID=" + StrUtil.EncryptUrl(info.ID));
                    }
                    else
                    {
                        Response.Redirect("Shopping3.aspx", true);
                    }
                }
                else
                {
                    memberInfo.Remain = memberInfo.Remain - info.TradeValue - info.Freight;
                    //this.Member.UpdateRemain(memberInfo.Remain, memberInfo.ID);
                    //memberInfo.Integral += (int)(info.TradeValue + info.Freight);
                    this.Member.Save(memberInfo);

                    info.PayState = (int)PayState.已支付;
                    this.Order.Save(info);
                    Order.dbOper.CommitTrans();

                    Response.Redirect("Shopping3.aspx", true);
                }

                
                
            }
            catch(Exception ex)
            {
                Order.dbOper.RollbackTrans();
                JSUtil.Alert("提交订单失败");
                ExceptionLogBO.Save(ex);
            }

        }

        //protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    BindAddress(int.Parse(drpArea.SelectedValue));
        //}
    }
}